package com.sc.byahi.user.server;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesService.OutputEncoding;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.OutputSettings;
import com.google.appengine.api.images.Transform;

public class Serve extends HttpServlet {
	// private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	// blobstoreService.serve(blobKey, res);
	// /serve?blob-key=ABCXYZ&r=[150|500|null]&c=[150|null]
	private Logger logger = Logger.getLogger("com.sc.byahi.user.server.Serve");

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
		try {
			String blobKeyStr = req.getParameter("blob-key");
			logger.log(Level.INFO, "Blob requested: " + blobKeyStr);
			BlobKey blobKey = new BlobKey(blobKeyStr);
			String r = req.getParameter("r");
			boolean resize = false;
			int s = 150;
			if (r != null) {
				resize = true;
				String side = req.getParameter("r");
				try {
					s = Integer.parseInt(side);
					if (s > 500)
						s = 150;
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
				logger.log(Level.INFO, "Resize requested with size: " + s);
			}
			String c = req.getParameter("c");
			boolean crop = false;
			double lx = .25;
			double ly = .25;
			double rx = .75;
			double ry = .75;
			if (c != null) {
				crop = true;
				String cropParams = req.getParameter("c");
				String[] strs = cropParams.split(",");

				try {
					lx = Double.parseDouble(strs[0]);
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
				try {
					ly = Double.parseDouble(strs[1]);
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
				try {
					rx = Double.parseDouble(strs[2]);
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
				try {
					ry = Double.parseDouble(strs[3]);
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
				logger.log(Level.INFO, "Crop requested.");

			}
			transform: {
				Image image = ImagesServiceFactory.makeImageFromBlob(blobKey);
				Transform transform = ImagesServiceFactory.makeResize(s, s);
				OutputSettings os = new OutputSettings(OutputEncoding.JPEG);
				os.setQuality(75);
				logger.log(Level.INFO, "Trying to transform image");
				ImagesService imagesService = ImagesServiceFactory.getImagesService();
				Image newImage = imagesService.applyTransform(transform, image, os);
				logger.log(Level.INFO, "Transform complete.");
				byte[] newImageData = newImage.getImageData();
				res.setHeader("Content-Type", "image/jpeg");
				res.setHeader("Content-Length", String.valueOf(newImageData.length));
				res.setHeader("Content-Disposition", "inline; filename=\"photo.jpeg\"");

				BufferedOutputStream output = null;
				try {
					output = new BufferedOutputStream(res.getOutputStream());
					output.write(newImageData);
				} finally {
					if (output != null)
						try {
							output.flush();
							output.close();
						} catch (IOException logOrIgnore) {

						}
				}
			}
			/*
			 * url: { BufferedInputStream bis = null; BufferedOutputStream output = null; try { String url = ImagesServiceFactory.getImagesService().getServingUrl(blobKey);
			 * 
			 * if (url.contains("0.0.0.0")) url = url.replace("0.0.0.0", "127.0.0.1"); else url = "http://127.0.0.1:8888" + url; if (resize) { url += "=s" + s; }
			 * 
			 * URL u = new URL(url); bis = new BufferedInputStream(u.openStream()); output = new BufferedOutputStream(res.getOutputStream()); byte[] buffer = new byte[8192]; for (int length = 0;
			 * (length = bis.read(buffer)) > 0;) { output.write(buffer, 0, length); } } catch (Exception e) { e.printStackTrace(); } finally { if (output != null) try { output.close(); } catch
			 * (IOException logOrIgnore) { } if (bis != null) try { bis.close(); } catch (IOException logOrIgnore) { } } }
			 */
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
